<?php
	// for POST string (used for counter sql injection)
	function sql_quote($value)
	{
		if(get_magic_quotes_gpc())
		{
			$value = stripslashes($value);
		}
		// check if this function exists
		if(function_exists("mysql_real_escape_string"))
		{
			$value = mysql_real_escape_string($value);
		}
		// for PHP < 4.3.0 use addslashes
		else
		{
			$value = addslashes($value);
		}
		return $value;
	}
	
	// for HTML POST string (used for counter sql injection)
	function sql_quote_html_sc_en($value)
	{	
		$value = htmlspecialchars($value, ENT_QUOTES);
		return $value;
	}
	
	// for HTML decode POST string (used for counter sql injection)
	function sql_quote_html_sc_de($value)
	{
		//$value = stripslashes($value);
		$value = htmlspecialchars_decode($value, ENT_NOQUOTES);
		$value = html_entity_decode($value);
		
		return $value;
	}
	
	function textarea_string($string)
	{
		$breaks = array("<br />","<br>","<br/>"); 
		$string = str_ireplace($breaks, "\r\n", $string); 
		$string = str_ireplace("\r\n\r\n", "\r\n", $string); 
		
		return $string;
	}
	
	//// Login Punishment ////
	function addLoginPunishment($ip)
	{
		$ip = sql_quote($ip);
		$sql = "select loginpunishmentcount, loginpunishmentrelease from tr_login_punishment where loginpunishmentip = '".$ip."' limit 0,1 ";
		$exe = mysql_query($sql) or die(mysql_error());
		$num = mysql_num_rows($exe);
		$row = mysql_fetch_array($exe);
		
		if($num > 0)
		{
			$limit = VALUE_LOGIN_LIMIT_CHANCE_MIN;	// set limit -------------------------------------
			
			$limit = $limit - 1;
			$count = $row['loginpunishmentcount'];
			
			$releasedate = $row['loginpunishmentrelease'];
			$now = GET_DATE;
			
			$input = $releasedate;				// input
			$date_calculate = strtotime($input);	
			
			// Punish Time
			$y = date("Y",$date_calculate) + SETTING_TIME_PUNISHMENT_YEAR;	// year
			$m = date("m",$date_calculate) + SETTING_TIME_PUNISHMENT_MONTH;	// month
			$d = date("d",$date_calculate) + SETTING_TIME_PUNISHMENT_DAY;	// day
			
			$H = date("H",$date_calculate) + SETTING_TIME_PUNISHMENT_HOUR;	// hour
			$i = date("i",$date_calculate) + SETTING_TIME_PUNISHMENT_MINUTE;	// minute
			$s = date("s",$date_calculate) + SETTING_TIME_PUNISHMENT_SECOND;	// second
			
			$result_date_calculate = mktime($H, $i, $s, $m, $d, $y);
			
			$input_date = strftime("%Y-%m-%d %H:%M:%S", $date_calculate);
			$result_date = strftime("%Y-%m-%d %H:%M:%S", $result_date_calculate);
			
			//echo $result_date;die();
			
			$maxlimit = VALUE_LOGIN_LIMIT_CHANCE_MAX;
			
			$maxlimit = $maxlimit - 1;
			if($count >= $maxlimit)
			{
				$count = $count + 1;
				$sql = "update tr_login_punishment set loginpunishmentstatus = '1', loginpunishmentcount = '".$count."', dateup = '".$now."' where loginpunishmentip = '".$ip."'  ";
			}
			else if($count == 0)
			{
				//echo "zxc"; die();
				$count = $count + 1;
				$sql = "update tr_login_punishment set loginpunishmentcount = '".$count."', loginpunishmentrelease = '".$now."', datein = '".$now."', dateup = '".$now."' where loginpunishmentip = '".$ip."'  ";
				
			}
			else if($count >= $limit)
			{
				//echo "qwe"; die();
				$count = $count + 1;
				$sql = "update tr_login_punishment set loginpunishmentcount = '".$count."', loginpunishmentrelease = '".$result_date."', dateup = '".$now."' where loginpunishmentip = '".$ip."'  ";
			}
			else if($count < $limit)
			{
				//echo "asd"; die();
				$count = $count + 1;
				$sql = "update tr_login_punishment set loginpunishmentcount = '".$count."', loginpunishmentrelease = '".$now."', dateup = '".$now."' where loginpunishmentip = '".$ip."'  ";
			}
			$exe = mysql_query($sql) or die(mysql_error());
		}
		else
		{
			$sql = "insert into tr_login_punishment (loginpunishmentid, loginpunishmentip, loginpunishmentcount, loginpunishmentstatus, loginpunishmentrelease, datein, dateup)
					values ('', '".$ip."', '1', '0', '".GET_DATE."', '".GET_DATE."', '')  
					";
			$exe = mysql_query($sql) or die(mysql_error());
		}
	}
	
	function checkLoginPunishment($ip)
	{
		$ip = sql_quote($ip);
		$grant = 0;
	
		$limit = VALUE_LOGIN_LIMIT_CHANCE_MIN;
		if(SETTING_CHECK_LOGIN_PUNISHMENT_MAX == 1)
		{
			$maxlimit = VALUE_LOGIN_LIMIT_CHANCE_MAX;
			
			if(($limit*2) > $maxlimit)
			{
				echo "INVALID SETTING LOGIN MAX CHANCE";die();
			}
		}
		
		$sql = "select loginpunishmentstatus, loginpunishmentcount, loginpunishmentrelease from tr_login_punishment where loginpunishmentip = '".$ip."' limit 0,1 ";
		$exe = mysql_query($sql) or die(mysql_error());
		$num = mysql_num_rows($exe);
		$row = mysql_fetch_array($exe);
		
		if($num > 0)
		{
			$limit = VALUE_LOGIN_LIMIT_CHANCE_MIN;
			$releasedate = trim($row['loginpunishmentrelease']);	// remove all space before and after variable releasedate
			$filter = array("-", ":", " ");
			$releasedate = str_replace($filter, "", $releasedate);	// replacing all character by filter
			
			
			$now = trim(GET_DATE);	// remove all space before and after variable now
			$filter = array("-", ":", " ");
			$now = str_replace($filter, "", $now);	// replacing all character by filter
			
			/*
			echo $releasedate;
			echo "<br />";
			echo $now;
			echo "<br />";
			*/
			if($row['loginpunishmentstatus']==1)
			{
				$grant = -2;
			}
			else if($releasedate > $now && $row['loginpunishmentcount'] >= $limit)
			{
				addLoginPunishment($ip);
				$grant = -1;
			}
			else
			{
				if($row['loginpunishmentcount'] >= $limit)
				{
					resetLoginPunishment($ip);
				}
				$grant = 1;
			}
		}
		else
		{
			$sql = "insert into tr_login_punishment (loginpunishmentid, loginpunishmentip, loginpunishmentcount, loginpunishmentstatus, loginpunishmentrelease, datein, dateup)
					values ('', '".$ip."', '0', '0', '".GET_DATE."', '".GET_DATE."', '')  
					";
			$exe = mysql_query($sql) or die(mysql_error());
			
			$grant = 1;
		}
		
		return $grant;
	}
	
	function resetLoginPunishment($ip)
	{
		$ip = sql_quote($ip);
		$sql = "select * from tr_login_punishment where loginpunishmentip = '".$ip."' limit 0,1 ";
		$exe = mysql_query($sql) or die(mysql_error());
		$num = mysql_num_rows($exe);
		$row = mysql_fetch_array($exe);
		
		if($num > 0)
		{
			$now = trim(GET_DATE);
			$sql = "update tr_login_punishment set loginpunishmentstatus = '0', loginpunishmentcount = '0', loginpunishmentrelease = '".$now."', datein = '".$now."', dateup = '".$now."' where loginpunishmentip = '".$ip."'  ";
			$exe = mysql_query($sql) or die(mysql_error());
		}
	}
	
	//// this page is log the activity on admin page ////
	function getFilenameWithoutExt($filename)
	{
			$raw_name = explode ("." , $filename);
			$name = $raw_name[0];
			$ext = $raw_name[1];
			
			$file_info = Array(
				0 => $name,
				1 => $ext);
			
			return $file_info;
	}
	
	////  ////
	function redirect_page($url)
	{
		if($url!='')
		{
			$redirect = '<meta http-equiv="refresh" content="0;URL='.$url.'" />';
			die();
		}
		else
		{
			$redirect = '<meta http-equiv="refresh" content="0;URL=index.php" />';
			die();
		}
		return $redirect;
		
	}
	
	////  ////
	function addLogByUsername($message)
	{
		$message = sql_quote($message);
		$userid = !empty($_SESSION['userid']) ? $_SESSION['userid'] : 0 ;
		$username = $_SESSION['username'];
		$log_message = $message." (".$username.")";
		$ip_addr = $_SERVER['REMOTE_ADDR'];
		$log_date = GET_DATE;
		
		$query = "INSERT INTO tr_log (logaction,logdate,userid,logip) VALUES ('$log_message','$log_date',$userid,'$ip_addr')";
		$hasil = mysql_query($query) or die(mysql_error());
		
	}
	
	////  ////
	function addLogByIP($message)
	{
		$message = sql_quote($message);
		$userid = 0 ;
		$username = "system";
		$ip_addr = $_SERVER['REMOTE_ADDR'];
		$log_message = $message." (".$ip_addr.")";
		$log_date = GET_DATE;
		
		$query = "INSERT INTO tr_log (logaction,logdate,userid,logip) VALUES ('$log_message','$log_date',$userid,'$ip_addr')";
		$hasil = mysql_query($query) or die(mysql_error());
		
	}


	//// Check Tables ////
	function table_exists($tablename, $database = false) 
	{
		$tablename = sql_quote($tablename);
		if(!$database) {
			$res = mysql_query("SELECT DATABASE()");
			$database = mysql_result($res, 0);
		}

		$res = mysql_query("
			SELECT COUNT(*) AS count 
			FROM information_schema.tables 
			WHERE table_schema = '".$database."' 
			AND table_name = '".$tablename."'
		");

		return mysql_result($res, 0) == 1;
	}
	
	
	function workspace_style()
	{
		$uri = $_SERVER['REQUEST_URI'];
		$uri_var = explode('/', $uri);
	
		if(!empty($uri_var[2])){$filename = $uri_var[2];}
		else{$filename = "";}
		
		if($filename == "management"){$ws_class = "workspace_management";}
		else if($filename == "module"){$ws_class = "workspace_modules";}
		else{$ws_class = "workspace_default";}
		
		echo "class='".$ws_class."'";
	}
	
	function check_user_module_process_privilege($userid, $usergroupid, $moduletype, $moduleid, $modulesubid, $action)
	{
		$userid = sql_quote($userid);
		$usergroupid = sql_quote($usergroupid);
		$moduletype = sql_quote($moduletype);
		$moduleid = sql_quote($moduleid);
		$modulesubid = sql_quote($modulesubid);
		$action = sql_quote($action);
		
		$value_return = false;
		
		if($usergroupid == 1)
		{
			$value_return = true;
		}
		else if($action == "ADD" || $action == "EDIT" || $action == "DELETE")
		{
			if($action == "ADD")
			{
				$string_sql_1 = "modulegroupprivilegeinsert";
			}
			else if($action == "EDIT")
			{
				$string_sql_1 = "modulegroupprivilegeupdate";
			}
			else if($action == "DELETE")
			{
				$string_sql_1 = "modulegroupprivilegedelete";
			}
		
			$sql = "select a.*
					from ms_user a
						left join ms_module_group_privilege b
							on a.usergroupid = b.usergroupid 
							and b.stsrc = 'A'
					where 	a.userid = ".$userid." 
						and a.usergroupid = ".$usergroupid." 
						and b.modulegroupprivilegeenable = 1
						and b.modulegroupprivilegetype = '".$moduletype."'
						and b.modulegroupprivilegemoduleid = ".$moduleid."
						and b.modulegroupprivilegemodulesubid = ".$modulesubid."
						and b.".$string_sql_1." = 1
						and a.stsrc = 'A'
					";
					
			//echo $sql;die();
			
			$exe = mysql_query($sql) or die(mysql_error());
			$num = mysql_num_rows($exe);
			if($num > 0)
			{
				$value_return = true;
			}
		}
		
		if($value_return == false)
		{
			setSessionErr();
		}
		
		return $value_return;
	}
	
	
	/**
	 * Crypt :: two-way encryption class using RIJNDAEL 256 AES standard
	 * @uses MCRYPT_RIJNDAEL_256
	 */
	class Crypt
	{
		private $key,$iv_size,$iv;
	 
		/**
		 * constructor
		 * @param $key (string:'DefaultKey')
		 * @return void
		 */
		function __construct($key='DefaultKey'){
			$this->iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
			$this->iv = mcrypt_create_iv($this->iv_size, MCRYPT_RAND);
			$this->key = trim($key);
		}
		
		public function encrypt($string){
			$string=trim($string);
			return base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $this->key, $string, MCRYPT_MODE_ECB, $this->iv));
		}
	 
		public function decrypt($string){
			return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256,$this->key,base64_decode($string),MCRYPT_MODE_ECB,$this->iv));
		}
	}
	
	// How to use !!
	//$crypt = new Crypt('1');	// set manual key
	//echo $crypt->encrypt('1').'<br/>'; // encrypt
	//echo $crypt->decrypt('BhXByjnrRxkOpZvzS71ggDrgbhDCoPrS94VqobUktis='); // decrypt
	
	function rijndael($mode, $string)
	{
		$key = RIJNDAEL_KEY;
		$value = "";
		$crypt = new Crypt($key);
		
		if($mode == "encode")
		{
			$value = $crypt->encrypt($string);
		}
		else if($mode == "decode")
		{
			$value = $crypt->decrypt($string);
		}
		
		return $value;
	}
	
	// for SEO URL string
	function seo_string($string)
	{
		$realname = $string;
	
		$seoname = preg_replace('/\%/',' percentage',$realname); 
		$seoname = preg_replace('/\@/',' at ',$seoname); 
		$seoname = preg_replace('/\&/',' and ',$seoname); 
		$seoname = preg_replace('/\s[\s]+/','-',$seoname);    // Strip off multiple spaces 
		$seoname = preg_replace('/[\s\W]+/','-',$seoname);    // Strip off spaces and non-alpha-numeric 
		$seoname = preg_replace('/^[\-]+/','',$seoname); // Strip off the starting hyphens 
		$seoname = preg_replace('/[\-]+$/','',$seoname); // Strip off the ending hyphens 
		$seoname = strtolower($seoname); 

		return $seoname; 
	}
	
	// for file URL string
	function file_string($string)
	{
		$filename = $string;
	
		$filename = str_replace("'", "", $filename);
		$filename = str_replace('"', "", $filename);
		
		//$filename = strtolower($filename); 

		return $filename; 
	}
	
	function privilege_check($userid, $usergroupid, $filetype, $filename)
	{
		$userid = sql_quote($userid);
		$usergroupid = sql_quote($usergroupid);
		$filetype = sql_quote($filetype);
		$filename = sql_quote($filename);
		
		$value_return = "0-0-0-0";
		
		/*
		echo "userid : ".$userid."<br />";
		echo "usergroupid : ".$usergroupid."<br />";
		echo "filetype : ".$filetype."<br />";
		echo "filename : ".$filename."<br />";
		die();
		*/
		
		if($usergroupid == 1)
		{
			$value_return = "1-1-1-1";
		}
		else
		{
			$sql = "select moduleid, modulesubid from ms_module_sub where modulesuburltype = '".$filetype."' and modulesuburlback = '".$filename."' and stsrc = 'A' ";
			$exe = mysql_query($sql) or die(mysql_error());
			$num = mysql_num_rows($exe);
			$row = mysql_fetch_array($exe);
			
			if($num > 0)
			{
				$sql_2 = "select 	b.modulegroupprivilegeenable,
									b.modulegroupprivilegeinsert, 
									b.modulegroupprivilegeupdate,
									b.modulegroupprivilegedelete	
						from ms_user a
							left join ms_module_group_privilege b
								on a.usergroupid = b.usergroupid and b.stsrc = 'A'
							left join ms_user_group c
								on a.usergroupid = c.usergroupid and c.stsrc = 'A'
						where 	b.modulegroupprivilegetype = '".$filetype."' 
							and b.usergroupid = ".$usergroupid."
							and b.modulegroupprivilegemoduleid = ".$row[0]."
							and b.modulegroupprivilegemodulesubid = ".$row[1]."
							and a.stsrc = 'A' ";
				$exe_2 = mysql_query($sql_2) or die(mysql_error());
				$num_2 = mysql_num_rows($exe_2);
				$row_2 = mysql_fetch_array($exe_2);
			}
			else
			{
				if($filetype == "management")
				{
					$sql = "select moduleadminid as moduleid from ms_module_admin where moduleadminurlback = '".$filename."' and stsrc = 'A' ";
				}
				else if($filetype == "module")
				{
					$sql = "select moduleid from ms_module where moduleurlback = '".$filename."' and stsrc = 'A' ";
				}
				
				$exe = mysql_query($sql) or die(mysql_error());
				$num = mysql_num_rows($exe);
				$row = mysql_fetch_array($exe);
				
				if($num > 0)
				{
					$sql_2 = "select 	b.modulegroupprivilegeenable,
										b.modulegroupprivilegeinsert, 
										b.modulegroupprivilegeupdate,
										b.modulegroupprivilegedelete	
							from ms_user a
								left join ms_module_group_privilege b
									on a.usergroupid = b.usergroupid and b.stsrc = 'A'
								left join ms_user_group c
									on a.usergroupid = c.usergroupid and c.stsrc = 'A'
							where 	b.modulegroupprivilegetype = '".$filetype."' 
								and b.usergroupid = ".$usergroupid."
								and b.modulegroupprivilegemoduleid = ".$row[0]."
								and b.modulegroupprivilegemodulesubid = 0
								and a.stsrc = 'A' ";
					$exe_2 = mysql_query($sql_2) or die(mysql_error());
					$num_2 = mysql_num_rows($exe_2);
					$row_2 = mysql_fetch_array($exe_2);
				}
			}
			
			$value_return = $row_2[0]."-".$row_2[1]."-".$row_2[2]."-".$row_2[3];
		}
		
		//echo $value_return; die();
		
		return $value_return;
	}
	
	function session_min_destroy()
	{
		session_unset();
		session_destroy();
		session_write_close();
	}
	
	function session_complete_destroy()
	{
		session_unset();
		session_destroy();
		session_write_close();
		setcookie(session_name(),'',0,'/');
		session_regenerate_id(true);
	}
	
	function setSessionMsg($message)
	{
		$_SESSION['msg'] = $message;
	}
	
	function setSessionErr()
	{
		$_SESSION['err'] = 1;
	}
	
	// Get String Between 2 String
	function get_string_between($string, $start, $end)
	{
		$string = " ".$string;
		$ini = strpos($string,$start);
		if ($ini == 0) return "";
		$ini += strlen($start);
		$len = strpos($string,$end,$ini) - $ini;
		return substr($string,$ini,$len);
	}
	
	function url_referer()
	{
		// Get referer
		if(isset($_SERVER['HTTP_REFERER']))
		{
			$http_referer = $_SERVER['HTTP_REFERER'];
			$referer = explode("?",$http_referer); //echo $http_referer;die();
			$url_referer = $referer[0]; //echo $url_referer;die();
		}
		return $url_referer;
	}
	
	function format_size($size) {
		// Bytes
		$sizes = array(" B", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
		
		if ($size == 0) { return('n/a'); } else {
		return (round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $sizes[$i]); }
		//return ($size/1024)." B";
	}
	
	function get_image_size($filename, $role)
	{
		$size = getimagesize($filename);
		$fp = fopen($filename, "rb");
		if ($size && $fp)
		{
			if($role == "width"){$result = $size[0];}
			if($role == "height"){$result = $size[1];}
		}
		else
		{
			$result = "Invalid File Type or an error occurred";
		}
		
		return $result;
	}
?>